"""
server-server views like join handlers and the like.

-builds the appropriate objects from json in the html request.
-sends to similarly named functions in "server_api.py"

"""
### Start of imports

# This line just better work...
from jackson import debug

# There's debug stuff for the rest
debug.pre_import(__name__)

debug.importing(__name__, 'jackson.extjson.ext_json')
import jackson.extjson.ext_json as json

debug.importing(__name__, 'urllib2', 3)
import urllib2

# let's pollute the namespace, shall we?
debug.importing(__name__, 'server_api from jackson.chord') 
from jackson.chord import server_api

debug.importing(__name__, 'HttpResponse from django.http')
from django.http import HttpResponse

debug.post_import(__name__)

### End of imports

def get_predecessor_handler(request):
    """ @change: 12-31-08: now uses ext_json
    """
    s = server_api.get_predecessor_handler()
    json_result = json.dumps(s)
    return HttpResponse(json_result, mimetype='application/json')

def get_successor_handler(request):
    """ @change: 12-31-08: now uses ext_json
    """
    s = server_api.get_successor_handler()
    json_result = json.dumps(s)
    return HttpResponse(json_result, mimetype='application/json')

def is_predecessor_handler(request):
    """ @rtype: boolean
    """
    context = [__name__, 'is_predecessor_handler()', []]
    debug.enter(context, None, 2)
    try:
        debug.comment(context, 'Unpacking data from request', 2)
        s = json.loads(request.REQUEST['data']) # this should be a key object (hex or something)
        debug.comment(context, 'Resovling query', 2)
        b = server_api.is_predecessor_handler(s)
        result = HttpResponse(json.dumps(b), mimetype='application/json')
    except Exception, e:
        debug.exception(context, str(e))
        result = HttpResponse('is_predecessor fail')
    debug.leave(context, { 'b' : b }, 2)
    return result

def join_handler(request):  
    """
    @todo: compare this with server_api.join_handler return types and logic
    @change: 12-31-08: now uses ext_json
    @change: 1-17-09: no keys here!
    """
    context = [__name__, 'join_handler()', []]
    debug.enter(context, None, 2)
    try:
        debug.comment(context, 'Extracting data from request', 2)
        r = json.loads(request.REQUEST['data']) # grab the joining server's Server object
        stuff_dict = server_api.join_handler(r) # pass it to my local join_handler
        debug.comment(context, 'parsing json welcome package', 2)
        json_result = json.dumps(stuff_dict)
        response = HttpResponse(json_result, mimetype='application/json')
    except Exception, e:
        print "chord.views.server.join_handler(): exception raised:",e
        debug.exception(context, str(e))
        response = HttpResponse("join fail")
    debug.leave(context, stuff_dict, 2)
    return response

def closest_preceding_finger_handler(request):  
    """ handles when someone needs to know who precedes some key.
    @rtype: a json'd server object
    """
    context = [__name__, 'closest_preceding_finger_handler()', []]
    debug.enter(context, None)
    try:
        debug.comment(context, 'Unpacking data')
        r = json.loads(request.REQUEST['data']) # grab the key we're asking about
        debug.comment(context, 'Calling into server_api')
        s = server_api.closest_preceding_finger_handler(r)
        result = HttpResponse(json.dumps(s), mimetype='application/json')
    except Exception, e:
        print "chord.views.server.closest_preceding_finger_handler(): exception raised:",e
        result = HttpResponse(json.dumps({ 'exception' : str(e) }))
    debug.leave(context, { 's' : s }) 
    return result

def leave_handler(request):
    """
    # @todo: compare this to the return type in net_requests.leave()
    # where do the keys come from?
    """
    context = [__name__, 'leave_handler()', []]
    debug.enter(context, None, 2)
    debug.comment(context, 'Extracting data from the request', 2)
    r = json.loads(request.REQUEST['data'])
    b = server_api.leave_handler(r)
    result = HttpResponse(json.dumps(b), mimetype='application/json')
    debug.leave(context, { 'b' : b }, 2)
    return result

def notify_handler(request):
    """ @change: 12-31-08: now uses ext_json
    """
    r = json.loads(request.read())
    server_api.notify_handler(r)
    json_result = json.dumps(None) # empty response, nothing needed
    return HttpResponse(json_result, mimetype='application/json')

def stabilize_handler(request):
    """ see the note in server_api.notify_handler()
    @change: 12-31-08: now uses ext_json
    """
    r = json.loads(request.read())
    server_api.stabilize_handler()
    json_result = json.dumps(None) # empty response, nothing needed
    return HttpResponse(json_result, mimetype='application/json')

def update_successor_handler(request):
    """ @change: 12-31-08: now uses ext_json
    """
    r = json.loads(request.REQUEST['data']) # this should be our server
    server_api.update_successor_handler(r)
    json_result = json.dumps(None) # empty response, nothing needed
    return HttpResponse(json_result, mimetype='application/json')

